package com.huihui.widget;

import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.Spanned;
import android.util.AttributeSet;

import java.util.HashMap;
import java.util.Set;
import java.util.regex.PatternSyntaxException;

/**
 * Created by yinsxi on 2018/8/31.
 */

public class PartColorTextView extends AppCompatTextView {
    private final String SRM="<font color=\"⊙\">%1$s</font>";//文字转换Hmtl的格式固定不要动
    private final String OF="⊙";//替换颜色的字符


    public PartColorTextView(Context context) {
        super(context);
    }

    public PartColorTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PartColorTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    public void setPartText(String allText,String keyText,int otherTextColor,int keyTextColor)
    {
        String NF = String.format("#%06X", 0xFFFFFF & keyTextColor);
        String replace = SRM.replace(OF, NF);
        String format = String.format(replace, keyText);
        try {
            String textStr = allText.replaceAll(keyText, format);
            Spanned spanned = Html.fromHtml(textStr);
            setTextColor(otherTextColor);
            setText(spanned);
        }catch (PatternSyntaxException e)
        {
            e.printStackTrace();
        }
    }
    public void setPartText(String allText, HashMap<String,Integer> keyColorMap, int otherTextColor)
    {
        Spanned spanned = null;
        String textStr=null;
        Set<String> keySet = keyColorMap.keySet();
        for (String s : keySet) {
            String NF = String.format("#%06X", 0xFFFFFF & keyColorMap.get(s));
            String replace = SRM.replace(OF, NF);
            String format = String.format(replace, s);
            try {
                if (textStr==null)
                {
                    textStr  = allText.replaceAll(s, format);
                }else
                {
                    textStr=textStr.replaceAll(s, format);
                }
            }catch (PatternSyntaxException e)
            {
                e.printStackTrace();
            }
        }
        setTextColor(otherTextColor);
        spanned= Html.fromHtml(textStr);
        setText(spanned);
    }


}
